import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/team_user_entity.dart';
import 'package:seedfour/app/remote/request.dart';

import '../../../services/api_service.dart';

class MineTeamLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = true.obs;
  var bottomTips = ''.obs;
  var teamUsers = <TeamUserData>[].obs;

  late ScrollController scrollController;
  late TextEditingController nameController;
  late TextEditingController mobileController;

  @override
  void onInit() {
    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getTeamInfo();
      }
    });

    nameController = TextEditingController();
    mobileController = TextEditingController();

    _getTeamInfo();

    super.onInit();
  }

  void _getTeamInfo() {
    teamUsers.clear();
    apiService.getTeamUsers().then((team) => {
          isLoading.value = false,
          if (team != null)
            {teamUsers.addAll(team.data ?? []), bottomTips.value = noMoreTip}
          else
            {bottomTips.value = noMoreTip}
        });
  }

  void onDeleteItem(int index) => request(
        () async {
          apiService
              .deleteEdit(teamUsers[index].uid)
              .then((value) => _getTeamInfo());
        },
        showLoading: true,
      );

  void onAddItem() => request(
        () async {
          apiService
              .addEdit(nameController.value.text, mobileController.value.text)
              .then((value) => _getTeamInfo());
        },
        showLoading: true,
      );

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }
}
